<?php

class CategoryController extends BaseAdminController {

    public $menu = array(
        array('label' => 'Create new category', 'url' => array('category/create')),
        array('label' => 'List of all categories', 'url' => array('category/list'))
    );

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow admin user to perform all actions
                'actions' => array('index', 'list', 'create', 'update', 'delete', 'search'),
                'users' => array(User::model()->getAdmin()->email),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Get all models.
     */
    public function actionIndex() {
        $this->redirect(array('list'));
    }

    /**
     * 
     */
    public function actionSearch() {
        $categorySearch = new Search;
        if (isset($_POST['Search'])) {
            $categorySearch->attributes = $_POST['Search'];
            $keyWord = $categorySearch->keyWord;
            $criteria = new CDbCriteria;
            $criteria->distinct = true;
            $criteria->condition = "parent_id is not null AND is_displayed = 1";
            if (strlen($keyWord) > 0) {
                $criteria->join = ' INNER JOIN category_detail d ON t.id=d.category_id AND d.name like :keyWord';
                $criteria->params = array(':keyWord' => '%' . $keyWord . '%');
            }
            $dataProvider = new CActiveDataProvider('Category', array(
                        'criteria' => $criteria,
                        'pagination' => array(
                            'pageSize' => Constant::ADMIN_LIST_SIZE,
                        ),
                    ));
            $categorySearch = new Search;
            $this->render('list', array(
                'categorySearch' => $categorySearch,
                'dataProvider' => $dataProvider,
            ));
        }
    }

    /**
     * Manages all models.
     */
    public function actionList() {
        $categorySearch = new Search;
        $criteria = new CDbCriteria;
        //$criteria->condition = "parent_id is not null";
        $dataProvider = new CActiveDataProvider('Category', array(
                    'criteria' => $criteria,
                    'pagination' => array(
                        'pageSize' => Constant::PAGE_SIZE,
                    ),
                ));

        $this->render('list', array(
            'categorySearch' => $categorySearch,
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'list' page.
     */
    public function actionCreate() {
        try {
            $language = 'en';
            $hasParent = false;
            $categoryTypes = Category::model()->getAllCategories($language, $hasParent);
            $category = new Category;
            $category->is_displayed = TRUE;
            $categoryDetails = array();
            for ($i = 0; $i < 1; $i++) {
                $categoryDetail = new CategoryDetail;
                if ($i == 0) {
                    $categoryDetail->language = 'en';
                } else {
                    $categoryDetail->language = 'vi';
                }
                $categoryDetails[] = $categoryDetail;
            }
            $message = '';

            if (isset($_POST['Category']) && isset($_POST['CategoryDetail'])) {
                // collects user input data
                $category->attributes = $_POST['Category'];
                if ($category->validate()) {
                    $valid = true;
                    if ($category->hasParent == FALSE) {
                        $category->parent_id = NULL;
                    }
                    foreach ($categoryDetails as $i => $categoryDetail) {
                        $categoryDetail->attributes = $_POST['CategoryDetail'][$i];
                        $categoryDetails[$i] = $categoryDetail;
                        $valid = $categoryDetail->validate() && $valid;
                    }
                    if ($valid) {
                        $transaction = $category->getDbConnection()->beginTransaction();
                        try {
                            if ($category->save()) {
                                foreach ($categoryDetails as $categoryDetail) {
                                    $categoryDetail->category_id = $category->id;
                                    $categoryDetail->save();
                                }
                                $transaction->commit();
                                Yii::app()->user->setFlash('success', Yii::t('category', 'Create new category successfully'));
                                $this->refresh();
                                $this->redirect(array('create'));
                            } else {
                                $message = Yii::t('category', Yii::t('category', 'Create new category failed'));
                            }
                        } catch (Exception $ex) {
                            $transaction->rollback();
                        }
                    } else {
                        $message = Yii::t('category', 'notValid');
                    }
                }
            }
            // displays the login form
            $this->render('create', array(
                'categoryTypes' => $categoryTypes,
                'category' => $category,
                'categoryDetails' => $categoryDetails,
                'message' => $message,
            ));
        } catch (Exception $ex) {
            throw new CHttpException(Yii::t('default', 'notExistWeb'));
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'list' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        try {
            $language = 'en';
            $hasParent = FALSE;
            $categoryTypes = Category::model()->getAllCategories($language, $hasParent);
            $category = $this->loadModel($id);
            $categoryDetails = $category->categoryDetails;
            $message = '';

            if (isset($_POST['Category']) && isset($_POST['CategoryDetail'])) {
                // collects user input data
                $category->attributes = $_POST['Category'];
                if ($category->validate()) {
                    $valid = true;
                    if ($category->hasParent == FALSE) {
                        $category->parent_id = NULL;
                    }
                    foreach ($categoryDetails as $i => $categoryDetail) {
                        $categoryDetail->attributes = $_POST['CategoryDetail'][$i];
                        $categoryDetails[$i] = $categoryDetail;
                        $valid = $categoryDetail->validate() && $valid;
                    }
                    if ($valid) {
                        $transaction = $category->getDbConnection()->beginTransaction();
                        try {
                            if ($category->save()) {
                                foreach ($categoryDetails as $categoryDetail) {
                                    $categoryDetail->category_id = $category->id;
                                    $categoryDetail->save();
                                }
                                $transaction->commit();
                                Yii::app()->user->setFlash('success', Yii::t('category', 'Update category successfully'));
                                $this->redirect(array('list'));
                            } else {
                                $message = Yii::t('category', Yii::t('category', 'Update category failed'));
                            }
                        } catch (Exception $ex) {
                            $transaction->rollback();
                        }
                    } else {
                        $message = Yii::t('category', 'notValid');
                    }
                }
            }

            $this->render('update', array(
                'categoryTypes' => $categoryTypes,
                'category' => $category,
                'categoryDetails' => $categoryDetails,
                'message' => $message,
            ));
        } catch (Exception $ex) {
            throw new CHttpException(Yii::t('default', 'notExistWeb'));
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $category = $this->loadModel($id);
            $category->delete();
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('list'));
        }
        else
            throw new CHttpException(400, Yii::t('default', 'notExistWeb'));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $category = Category::model()->findByPk($id);
        if ($category === null)
            throw new CHttpException(404, Yii::t('default', 'notExistWeb'));
        return $category;
    }

}